//
//  MsgListViewController.m
//  Kfangchan
//
//  Created by 朋飞 on 14-11-19.
//  Copyright (c) 2014年 Beijing Renjuren Network Technology Co., Ltd. All rights reserved.
//

#import "MsgListViewController.h"

@interface MsgListViewController (){
    UITapGestureRecognizer *tap;
    UIView *emptyView;
    
}
@property (nonatomic) int cpage;

@property (strong, nonatomic) IBOutlet UITableView *msgTableView;
@property (strong, nonatomic) IBOutlet UIView *msgView;

@property (strong, nonatomic) NSMutableArray *msgArray;

@end

@implementation MsgListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.titleView = [[Theam currentTheam] navigationTitleViewWithTitle:@"消息列表"];
    self.navigationItem.leftBarButtonItem = [[Theam currentTheam] navigationBarLeftButtonItemWithImage:[UIImage imageNamed:@"nav_back.png"] Target:self Selector:@selector(back)];
    __weak MsgListViewController *weak_self = self;
    //header
    [self.msgTableView addHeaderWithCallback:^{
        [weak_self initList];
    } andIsChat:YES andIsOther:YES];
    //footer
    [self.msgTableView addFooterWithCallback:^{
        weak_self.cpage++;
        [weak_self loadData];
    }];
    self.msgTableView.size = CGSizeMake(self.msgTableView.width, ScreenHeight - 60);
    
    [self initEmptyView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.msgArray == nil || self.msgArray.count == 0) {
        [self initList];
    }
}



#pragma mark - UITableVIew
#pragma mark 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.msgArray count];
}

#pragma mark
#pragma mark UITableViewDatasource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Notice *item=(Notice*)[self.msgArray objectAtIndex:indexPath.row];
    if(item.isExpand==NO){
        return 50;
    }
    
    ////////mosn
    ///262是labe的width
    CGRect rect = [NSString heightForString:item.content Size:CGSizeMake(262, 999) Font:[UIFont systemFontOfSize:15]];
    ////////
    
    return 130-38+rect.size.height;  ///130是cell现在高度，38是计算前的contentlabe的高度，rect height是计算后的高度
    
}


#pragma mark 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"MsgTableViewCell";
    Notice *entity = self.msgArray[indexPath.row];
    
    MsgTableViewCell *cell = (MsgTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        NSArray *cells = [[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil];
        cell = [cells objectAtIndex:0];
        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    [cell initCell:entity];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    MsgTableViewCell *cell = (MsgTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    //    if(cell.revealing==YES){
    //        cell.revealing=NO;
    //        return;
    //    }
    Notice *item=(Notice*)[self.msgArray objectAtIndex:indexPath.row];
    
    if(item.status == 0){
        [self read:item];
        item.status = 1;
    }
    
    item.isExpand=!item.isExpand;
    cell.notice=item;
    
    
    
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
}

#pragma mark -
#pragma mark 空结果页
- (void)initEmptyView {
    if(emptyView == nil) {
        emptyView = [[UIView alloc] initWithFrame:self.msgView.bounds];
        UIImageView *emptyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 45, 320, 204)];
        emptyImageView.image = [UIImage imageNamed:@"no_msg.png"];
        [emptyView addSubview:emptyImageView];
    }
}


#pragma mark - 列表相关
#pragma mark 初始化
- (void)initList {
    self.cpage = 1;
    if (self.msgArray == nil) {
        self.msgArray = [NSMutableArray array];
    }
    [self loadData];
}
#pragma mark 加载数据
- (void)loadData {
    
    __weak MsgListViewController *weak_self = self;
    NSDictionary *param = @{
                            @"cpage": [NSString stringWithFormat:@"%i", self.cpage]
                            };
    MKNetworkOperation *operation = [[BaseEngine sharedEngine]RunRequest:[param mutableCopy] path:KFC_MESSAGE_LIST completionHandler:^(id responseObject) {
        
        if (weak_self.cpage==1) {
            [weak_self.msgArray removeAllObjects];
        }
        
        id totalPages = [responseObject objectForKey:@"totalPages"];
        if (weak_self.cpage >= [totalPages intValue]) {
            [weak_self.msgTableView setFooterHidden:YES];
        } else {
            [weak_self.msgTableView setFooterHidden:NO];
        }
        
        id list = [responseObject objectForKey:@"list"];
        if (![list isKindOfClass:[NSNull class]]) {
            NoticeList *msgList = [[NoticeList alloc] initWithArray:list];
            [weak_self.msgArray addObjectsFromArray:msgList.array];
        }
        
        if (weak_self.msgArray.count == 0) {
            [weak_self.msgTableView addSubview:emptyView];
        } else {
            [emptyView removeFromSuperview];
        }
        
        [weak_self.msgTableView reloadData];
    } errorHandler:^(NSError *error) {
        showCustomAlertMessage(@"网路错误");
        [weak_self.msgTableView headerEndRefreshing];
        [weak_self.msgTableView setFooterHidden:YES];
    } finishHandler:^(id responseObject) {
        [weak_self.msgTableView headerEndRefreshing];
        [weak_self.msgTableView footerEndRefreshing];
    }];
    [self.opHandlers addObject:operation];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark  阅读
#pragma mark
-(IBAction) read: (Notice *)item{
    //    BOOL verify = [self verify:self.phoneTextField.text];
    //    if(verify){
    // 构建请求参数
    NSDictionary *param = @{
                            @"noticeId":[NSString stringWithFormat:@"%d",item.pkid]
                            };
    // 请求
    MKNetworkOperation *operation = [[BaseEngine sharedEngine]RunRequest:[param mutableCopy] path:KFC_MESSAGE_READ completionHandler:^(id responseObject) {
        if(responseObject){
            
            item.status = 1;
            
        }
        
    } errorHandler:^(NSError *error){
        
        showCustomAlertMessage(@"网路错误");
        
    }finishHandler:^(id responseObject) {
        
    }];
    
    [self.opHandlers addObject:operation];
    
    //  }
}


#pragma mark -
#pragma mark
- (void)back {
    if(self.fromflag == 1){
        self.fromflag    = 0;
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
        
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


@end
